package com.c4p.im.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.c4p.config.WebSocketProperties;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
@ChannelHandler.Sharable
public class UserInfoExactHandler extends ChannelInboundHandlerAdapter {

    public static final AttributeKey<String> USER_INFO_ATTRIBUTEKEY = AttributeKey.valueOf("userInfo");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = ((FullHttpRequest) msg);
            if (request.uri().contains(SpringUtil.getBean(WebSocketProperties.class).getPath())) {
//            todo 如果是http请求，请求路径为ws,代表着首次连接，那么可以根据token获取用户信息进行业务处理
                String token = Objects.requireNonNull(request.headers().get("token"));

                ctx.channel().attr(USER_INFO_ATTRIBUTEKEY).set(token);
                ctx.fireUserEventTriggered(token);

                //此处需要重置uri，否则会无法连接。
                //通过重载解决。 参见 https://www.cnblogs.com/ocean234/p/14105341.html
                // request.setUri(SpringUtil.getBean(WebSocketProperties.class).getPath());
            }else {
                return;
            }
        }
        super.channelRead(ctx, msg);
    }
}
